from rest_framework.response import Response
from rest_framework.decorators import action
from rest_framework.viewsets import ModelViewSet
from questions.models import Label
from questions.serializers import LabelSerializerSimple

class GetViewSet(ModelViewSet):
    queryset = Label.objects.all()
    # 揣培洋 --4.1 所有标签信息 GET/labels/
    def list(self, request):
        labels = self.get_queryset()
        s = LabelSerializerSimple(instance=labels, many=True)
        return Response(s.data)


    # 揣培洋 -- 4.2 用户关注的标签  GET /labels/users/
    @action(methods=['get'], detail=False)
    def users(self, request):
        try:
            user = self.request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            labels = user.labels.all()
            sss = LabelSerializerSimple(instance=labels, many=True)
            return Response(sss.data)
        else:
            return Response([])











from rest_framework.viewsets import ModelViewSet

from questions.models import Question
from questions.serializers import QuestionSerializer, QuestionmessSerializer


# Create your views here.
#范璇 -- 4.问答question
#范璇 -- 4.7问题详情GET/questions/id
class Questions(ModelViewSet):
    serializer_class = QuestionmessSerializer
    queryset = Question.objects.all()

    def get(self, request, *args, **kwargs):
        queryset = self.get_queryset()
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


class QuestionsAnswer(ModelViewSet):
    serializer_class = QuestionSerializer
    queryset = Question.objects.all()

    # 范璇 --4.4最热回答的问题GET/questions/{id}/label/hot/
    def hot(self, request, *args, **kwargs):
        queryset = self.get_queryset().order_by("reply")
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    # 范璇 --4.3最新回答的问题GET/questions/{id}/label/new/
    def new(self, request, *args, **kwargs):
        queryset = self.get_queryset().order_by('-replytime')
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)

    # 范璇 --4.5等待回答的问题GET/questions/{id}/label/wait/
    def wait(self, request, *args, **kwargs):
        queryset = self.get_queryset().filter(reply=0)
        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)


    # 范璇 --4.6发布问题GET/questions
    def create(self, request, *args, **kwargs):

        serializer = self.get_serializer(data=request.data)

        serializer.is_valid(raise_exception=True)
        serializer.save()

        return Response(serializer.data)

    #范璇 --4.8问题有用PUT/questions/{id}/useful/
    def useful(self, request, *args, **kwargs):
        recruit = self.get_serializer()
        recruit.useful_count += 1
        recruit.save()
        return Response({'success':True, 'message':'保存成功'})

    # 范璇 --4.9问题无用PUT/questions/{id}/useful/
    def unuseful(self, request, *args, **kwargs):

        recruit = self.get_serializer()
        recruit.unuseful_count += 1
        recruit.save()
        return Response({'success':True, 'message':'保存成功'})

    #
        # questions = Question.objects.all().order_by("replay")
        #
        # list = []
        # for question in questions:
        #     list.append({
        #         "createtime":question.createtime,
        #         'labels': question.labels,
        #         'reply' : question.reply,
        #         'replyname' : question.replyname,
        #         'replytime' : question.replytime,
        #         'title' : question.title,
        #         'unuseful_count' : question.unuseful_count,
        #         'useful_count' : question.useful_count,
        #         'user' : question.user,
        #         'visits' : question.visits
        #     })
        #
        #
        #
        # return JsonResponse({'code':0,
        #                      'errmsg':'ok',
        #                      'createtime':createtime,
        #                      'labels':labels,
        #                      'reply':reply,
        #                      "replyname":replyname,
        #                      'replytime':replytime,
        #                      'title':title,
        #                      'unuseful_count':unuseful_count,
        #                      'useful_count':useful_count,
        #                      'user':user,
        #                      'visits':visits})

from django.http import JsonResponse
from django_redis import get_redis_connection
from rest_framework.generics import ListAPIView
from rest_framework.permissions import IsAdminUser
from rest_framework_mongoengine.viewsets import ModelViewSet

from questions.models import Label
from questions.models import Reply
from questions.serializer import LabelSerializer_lxy
from users.models import User


# 李钰譞,备用,勿删
# class ReplyView(View):
#     def post(self, request):
#         json_dict = json.loads(request.body)
#         problem = json_dict.get('problem')
#         content = json_dict.get('content')
#         type = json_dict.get('type')
#         parent = json_dict.get('parent')
#         lxy = json_dict.get('lxy')
#         # user = request.user
#
#         if not all([problem, content, type]):
#             return JsonResponse({'code': 400,
#                                  'errmsg': 'NODATA'})
#
#         if parent and type == 1:
#             try:
#                 Reply.objects.create(user_id=lxy, problem=problem, type=type, parent=parent,
#                                      content=content)
#             except Exception as e:
#                 return JsonResponse({'success': False, 'message': '回答错误'})
#             else:
#                 return JsonResponse({'success': True, 'message': '回答成功'})
#
#         elif type in [2, 3]:
#             try:
#                 reply = Reply.objects.create(user_id=lxy, problem_id=problem, type=type, content=content)
#                 print(reply)
#             except Exception as e:
#                 return JsonResponse({'success': False, 'message': '回答错误'})
#             else:
#                 return JsonResponse({'success': True, 'message': '回答成功'})
#         else:
#             return JsonResponse({'success': False, 'message': '回答错误'})


# class ReplyUseful(View):
#     def put(self, request, pk):
#         # user = request.user
#         json_dict = json.loads(request.body)
#         lxy = json_dict.get('id')
#         try:
#             reply = Reply.objects.get(user_id=lxy, id=pk)
#         except Exception as e:
#             return JsonResponse({'success': False, 'message': '设置问题有误'})
#         reply.useful_count += 1
#         reply.save()
#         return JsonResponse({'success': True, 'message': '回答有用'})


# class ReplyUnuseful(View):
#     def put(self, request, pk):
#         # user = request.user
#         json_dict = json.loads(request.body)
#         lxy = json_dict.get('id')
#         try:
#             reply = Reply.objects.get(user_id=lxy, id=pk)
#         except Exception as e:
#             return JsonResponse({'success': False, 'message': '设置问题有误'})
#         reply.unuseful_count += 1
#         reply.save()
#         return JsonResponse({'success': True, 'message': '回答无用'})


# class LabelFocusin(View):
#     def put(self, request, pk):
#         # user = request.user
#         json_dict = json.loads(request.body)
#         lxy = json_dict.get('id')
#         try:
#             user = User.objects.get(id=lxy)
#             Label.objects.get(id=pk).users.add(user)
#         except Exception as e:
#             return JsonResponse({'success': False, 'message': '关注出错'})
#         return JsonResponse({'success': True, 'message': '关注成功'})


# class LabelFocusout(View):
#     def put(self, request, pk):
#         # user = request.user
#         json_dict = json.loads(request.body)
#         lxy = json_dict.get('id')
#         try:
#             user = User.objects.get(id=lxy)
#             Label.objects.get(id=pk).users.remove(user)
#         except Exception as e:
#             return JsonResponse({'success': False, 'message': '取消关注出错'})
#         return JsonResponse({'success': True, 'message': '取消关注成功'})


# 李钰譞
class LabelViewLxy(ListAPIView):
    permission_classes = [IsAdminUser]
    serializer_class = LabelSerializer_lxy
    queryset = Label.objects.all()


# 李钰譞
class ReplyViewLxy(ModelViewSet):
    permission_classes = [IsAdminUser]
    queryset = Reply.objects.all()

    def reply(self, request):
        user_id = request.user.id
        type = request.data.get('type')
        parent = request.data.get('parent')

        if parent and type == 1:
            try:
                Reply.objects.create(user_id=user_id, **request.data)
            except Exception as e:
                return Response({'success': False, 'message': '回答错误'})
            else:
                return Response({'success': True, 'message': '回答成功'})

        elif type in [0, 2] and (not parent):
            try:
                Reply.objects.create(**request.data)
            except Exception as e:
                return Response({'success': False, 'message': '回答错误'})
            else:
                return Response({'success': True, 'message': '回答成功'})
        else:
            return Response({'success': False, 'message': '回答错误'})

    def useful(self, request, pk):
        user = request.user
        redis_conn = get_redis_connection('default')
        flag = redis_conn.hget("reply_userful_%s" % user.id, pk)
        if flag:
            return JsonResponse({'success': False, 'message': '请不要重复操作'})

        else:
            reply = Reply.objects.get(id=pk)
            reply.useful_count += 1
            reply.save()
            redis_conn.hset("reply_userful_%s" % user.id, pk, 1)
        return JsonResponse({'success': True, 'message': '设置有用成功'})

    def unuseful(self, request, pk):
        user = request.user
        redis_conn = get_redis_connection('default')
        flag = redis_conn.hget("reply_unuserful_%s" % user.id, pk)
        if flag:
            return JsonResponse({'success': False, 'message': '请不要重复操作'})
        else:
            reply = Reply.objects.get(id=pk)
            reply.unuseful_count += 1
            reply.save()
            redis_conn.hset("reply_unuserful_%s" % user.id, pk, 1)
        return JsonResponse({'success': True, 'message': '设置有用成功'})

    def LabelFocusin(self, request, pk):
        user_id = request.user.id
        try:
            user = User.objects.get(id=user_id)
            Label.objects.get(id=pk).users.add(user)
        except Exception as e:
            return Response({'success': False, 'message': '关注出错'})
        return Response({'success': True, 'message': '关注成功'})

    def LabelFocusout(self, request, pk):
        user_id = request.user.id
        try:
            user = User.objects.get(id=user_id)
            Label.objects.get(id=pk).users.remove(user)
        except Exception as e:
            return Response({'success': False, 'message': '取消关注出错'})
        return Response({'success': True, 'message': '取消关注成功'})

